package com.mvp.base;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.jakewharton.rxbinding3.view.RxView;
import com.mvp.R;
import com.mvp.common.LocalManageUtil;
import com.mvp.refresh.RefreshViewManager;
import com.mvp.ui.dialog.LoadingDialog;
import com.mvp.widget.bottomtab.BottomTabManagerInter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.message.PushAgent;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;

import static timber.log.Timber.d;


/**
 * Created by zhangyuncai on 2018/9/11.
 */
public abstract class BaseAppCompatActivity extends AppCompatActivity implements LoadMvpView, View.OnClickListener, RefreshViewManager , BottomTabManagerInter {

    private LoadingDialog _processBar;
    public CompositeDisposable composite;
    private Unbinder unBinder;
    public String TAG = "当前activity==";
    protected BaseAppCompatActivity mActivity;
    protected WeakReference<Activity> activityWeakReference;

    @Override
    public void checkTabItem(int index) {

    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LocalManageUtil.attachBaseContext(newBase));
    }

    protected abstract int getLayoutId();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        activityWeakReference = new WeakReference<>(this);
        PushAgent.getInstance(mActivity).onAppStart();
        //获取当前页面类名 方便查找定位
        Log.e(TAG, getClass().getSimpleName());
        setContentView(R.layout.activity_baseactivity);
//        ViewStub vs_content=findViewById(R.id.vs_content);
//        vs_content.setLayoutResource(getLayoutId());
//        vs_content.inflate();
        setContentView(getLayoutId());
        setContentViewAfter();
        unBinder = ButterKnife.bind(this);
        this.composite = new CompositeDisposable();

    }

    protected void setContentViewAfter() {

    }


    /**
     * 空方法,无实质意义,仅仅方便敲写代码
     */
    protected void initView() {

    }

    /**
     * 空方法,无实质意义,仅仅方便敲写代码
     */
    protected void initData() {

    }

    /**
     * 空方法,无实质意义,仅仅方便敲写代码
     */
    protected void initEvent() {

    }

    /**
     * 防止双击
     *
     * @param v
     */
    public void onFilterDoubleClick(View v) {
        Disposable subscribe = RxView.clicks(v)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(unit -> {
                    onClick(v);
                });
        composite.add(subscribe);
    }

    @Override
    public void onClick(View v) {

    }


    /**
     * 设置全透明状态栏
     */
    protected void setStatusTrans() {
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
    }

    /**
     * 加载弹出窗口,具体由showDialog实现
     */
    @Override
    public void showLoadingBar(Object showTag) {
        Timber.v("Showing loading bar:msg:" + showTag + ",showDialogCout:" + showDialogCout);
        showDialog(showTag);
    }

    /**
     * 关闭弹出窗口,具体由closeDialog实现
     */
    @Override
    public void dismissLoadingBar(Object dississTag) {
        Timber.v("dismiss Loading Bar.showDialogCout:" + showDialogCout);
        closeDialog(dississTag);
    }

    @Override
    public void showLoadingFailureError(Throwable throwable) {
        d("--->>>>>>>>---" + throwable.getMessage());
        Timber.v("Showing loading failure layouts.");
        closeDialog("");
    }

    private int showDialogCout = 0;//显示dialog的次数,原则上是弹出一次dialog,才可以关闭一次dialog

    /**
     * 真正弹出加载窗口,内容代码可以更换为其他
     *
     * @param showTag 标记字符,当showTag=false,表示不弹出窗口
     */
    private void showDialog(Object showTag) {
        if (showTag != null && showTag instanceof Boolean) {
            //不弹出dialog
            Boolean b = (Boolean) showTag;
            if (!b) {
                d("--->>>>>>>>---showDialog不弹出!!");
                return;
            }
        }
        String message = getString(R.string.loading);
        if (showTag != null) {
            message = showTag.toString();
        }
        Disposable subscribe = Observable.just(message)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (showDialogCout == 0) {
                        showDialogCout = 0;
                    }
                    showDialogCout++;
                    if (_processBar == null) {
                        _processBar = new LoadingDialog(this, s);
                        _processBar.setCanceledOnTouchOutside(false);
                        _processBar.setCancelable(true);
                        _processBar.setOnDismissListener(dialog -> {
                            showDialogCout = 0;
                        });
                    } else {
                        _processBar.setMessage(s);
                    }
                    if (!_processBar.isShowing()) {
                        _processBar.show();
                    }

                }, throwable -> {
                    throwable.printStackTrace();
                });
        composite.add(subscribe);


    }

    /**
     * 真正关闭加载窗口,内容代码可以更换为其他
     *
     * @param dississTag 关闭标记字符
     */
    private void closeDialog(Object dississTag) {
        if (null != _processBar) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (_processBar.isShowing()) {
                        showDialogCout--;
                        /**
                         * 强行关闭弹窗
                         */
                        if (TextUtils.equals(dississTag + "", "all")) {
                            showDialogCout = 0;
                        }
                        if (showDialogCout <= 0) {
                            showDialogCout = 0;
                            _processBar.cancel();
                            if (refreshViewList != null) {
                                for (WeakReference<SmartRefreshLayout> smartRefreshLayoutWeakReference : refreshViewList) {
                                    if (smartRefreshLayoutWeakReference.get() != null) {
                                        smartRefreshLayoutWeakReference.get().finishLoadMore();
                                        smartRefreshLayoutWeakReference.get().finishRefresh();
                                    }
                                }
                                refreshViewList.clear();
                            }
                        }
                    }
                }
            });
        }
    }

    private List<WeakReference<SmartRefreshLayout>> refreshViewList;

    @Override
    public void addView(@NotNull View view) {
        if (refreshViewList == null) {
            refreshViewList = new ArrayList<>();
        }
        refreshViewList.add(new WeakReference<SmartRefreshLayout>((SmartRefreshLayout) view));
    }

    /**
     * 在布局中监听backClick
     *
     * @param v
     */
    public void backClick(View v) {
        finish();
    }

    @Override
    protected void onDestroy() {
        if (composite != null && !composite.isDisposed()) {
            composite.dispose();
        }
        if (unBinder != null && unBinder != Unbinder.EMPTY) {
            unBinder.unbind();//ButterKnife解绑
            unBinder = null;
        }
        if (_processBar != null) {
            if (_processBar.isShowing()) {
                _processBar.cancel();
            }
            _processBar = null;
        }
        super.onDestroy();
    }
}
